import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * class that make the output graphs
 *
 */
public class OutputGraphs {
	
	
	BufferedWriter bufferOut1;
	BufferedWriter bufferOut2;
	BufferedWriter bufferOut3;
	BufferedWriter bufferOut4;
	private int[] fitness;
	private SortingNetwork[] population;
	private FitnessCalculator fitnessFunction;
	
	/**
	 * C'tor
	 */
	public OutputGraphs()
	{
		 try {
				bufferOut1=new BufferedWriter(new FileWriter("out1.txt"));
				bufferOut2=new BufferedWriter(new FileWriter("out2.txt"));
				bufferOut3=new BufferedWriter(new FileWriter("out3.txt"));
				bufferOut4=new BufferedWriter(new FileWriter("out4.txt"));
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	/**
	 * calculate the avg fitness
	 * @return the avgFitness of exactly population 
	 */
	public double FitnessAVG()
	{
		double avg=0;
		for(int i=0; i<fitness.length; i++)
		{
			avg+=fitness[i];
		}
		avg=avg/fitness.length;
		return avg;
		
	}

	/**
	 * run on population and calculate the avg components
	 * @return the avg components 
	 */
	public int componenetsAVG()
	{
		int components=0;
		for(int i=0; i<population.length; i++)
		{
			components+=population[i].getNetwork().size();
		}
		components=components/population.length;
		return components;
	}
	
	/***
	 * 
	 * @return the avg of all:(avg of the examples placed correct at a network)
	 */
	public double placedCorrectAVG()
	{
		double placedCorrect=0;
		for(int i=0; i<population.length; i++)
		{
			placedCorrect+=fitnessFunction.placedCorrect(population[i]);
		}
		placedCorrect=1.0*placedCorrect/population.length;
		return placedCorrect;
	}
	
	/***
	 * build the output file
	 * @param fitnessFunction
	 * @param population
	 * @param fitness
	 * @param max
	 */
	public void outToFile(FitnessCalculator fitnessFunction,SortingNetwork[] population , int[] fitness, int max) {
		this.fitness=fitness;
		this.population=population;
		this.fitnessFunction=fitnessFunction;
		try {
			bufferOut1.write(max +"\n\r");
			bufferOut2.write(FitnessAVG()+"\n\r");
			bufferOut3.write(componenetsAVG()+"\n\r");
			bufferOut4.write(placedCorrectAVG()+"\n\r");
			bufferOut1.flush();
			bufferOut2.flush();
			bufferOut3.flush();
			bufferOut4.flush();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	 
}
